<?php
/**
 * Created by PhpStorm.
 * User: folie
 * Date: 2017/11/17
 * Time: 14:23
 */

namespace Home\Service;

use Home\Service\Ancun;

class AncunService {
    private $apiAddress = "http://openapi.ancun.com/open"; //api地址
//    private $apiAddress = "http://pre-openapi.ancun-inc.com/open"; //api地址
    private $accessKey  = "84b3e37dc12447edb7b5b527679b93ca";       //api access key
//    private $accessKey  = "b9f87b7d27474881f56a117ae3f17e94";       //api access key测试
    private $secretKey  = "07a8a7b92546bd390359b0add00535e25d369502";//api secret key
//    private $secretKey  = "0c5e7dc8bdcc566e525e2739824aa22e64d12cc3";//api secret keyc测试
//
    private $data = [];  //参数
    private $list = [];  //文件列表

    private $errorMsg;//错误信息

    private $opsResponse = null;
    //设置数据
    public function __set($name, $value) {
        $this->data[$name] = $value;
    }

    //获取数据
    public function __get($name) {
        return $this->data[$name];
    }

    /**
     * 制作人名章
     *
     * @param null $data 人名章的参数，如果已经调用setData设置了参数可以不用设置
     *
     * @return Ancun\AncunOpsResponse  code:100000 成功,其他失败; data:String
     */
    public function awardCaForPersonal($data = NULL) {
        if($data) {
            $this->setData($data);
        }
        $opsRequest = new Ancun\AncunOpsRequest();
        $opsRequest->setData($this->data);
        $opsRequest->setList($this->list);
        $opsClient = new Ancun\AncunOpsClient($this->apiAddress, $this->accessKey, $this->secretKey);
        $this->opsResponse = $opsClient->awardCaForPersonal($opsRequest);
        return $this->opsResponse;
    }

    /**
     * 制作企业章
     *
     * @param null $data 人名章的参数，如果已经调用setData设置了参数可以不用设置
     *
     * @return Ancun\AncunOpsResponse  code:100000 成功,其他失败; data:String
     */
    public function awardCaForCompany($data = NULL) {
        if($data) {
            $this->setData($data);
        }
        $opsRequest = new Ancun\AncunOpsRequest();
        $opsRequest->setData($this->data);
        $opsRequest->setList($this->list);
        $opsClient = new Ancun\AncunOpsClient($this->apiAddress, $this->accessKey, $this->secretKey);
        $this->opsResponse = $opsClient->awardCaForCompany($opsRequest);
        return $this->opsResponse;
    }

    /**
     * 获取印章信息
     *
     * @param null $data 签章主体 人的证件号
     *
     * @return Ancun\AncunOpsResponse    code:100000 成功,其他失败; data:String
     */
    public function obtainPersonSeal($identNo) {
        $map = [
            'itemKey' => '',
            'identNo' => $identNo,
        ];
        $map["preserveData"] = json_encode($map);
        $opsRequest = new Ancun\AncunOpsRequest();
        $opsRequest->setData($map);
        $opsClient = new Ancun\AncunOpsClient($this->apiAddress, $this->accessKey, $this->secretKey);
        $this->opsResponse = $opsClient->obtainPersonSeal($opsRequest);
        return $this->opsResponse;
    }

    /**
     * 保全数据
     *
     * @param null $data
     *
     * @return Ancun\AncunOpsResponse
     */
    public function save($data = NULL) {
        if($data) {
            $this->setData($data);
        }
        $opsRequest = new Ancun\AncunOpsRequest();
        $opsRequest->setItemkey($this->data['itemKey']);
        $opsRequest->setData($this->data);
        $opsRequest->setList($this->list);
        $opsClient = new Ancun\AncunOpsClient($this->apiAddress, $this->accessKey, $this->secretKey);
        $this->opsResponse = $opsClient->save($opsRequest);
        return $this->opsResponse;
    }

    /**
     * 用户信息保全
     * @param $data
     *
     * @return Ancun\AncunOpsResponse
     */

    /**
     * 用户 托管信息 追加列表
     * @param $data
     *
     * @return Ancun\AncunOpsResponse
     */
    /**
     * 借款保全
     * @param $data
     */
    public function loanSave($data){
        $data['itemKey'] = 'I-0577003';
        $data['flowNo'] = 'X-1381001';
        $this->setData($data);
        return $this->save();
    }

    /**
     * 还款保全
     * @param $data
     */
    public function repaymentSave($data){
        $data['itemKey'] = 'I-0577002';
        $data['flowNo'] = 'X-1197002';
        $this->setData($data);
        return $this->save();
    }

    /**
     * 设置参数
     *
     * @param $data  根据需要的类型调用
     */
    public function setData($name,$value = null) {
        if(is_array($name)) {
            $this->data = array_merge($this->data, $name);
            return $this->data;
        }
        $this->data[$name] = $value;
        return $this->data;
    }

    /**
     * 添加文件
     *
     * @param $fileFullPath  文件路径
     * @param $fileName      文件名称
     *
     * @return mixed   数据列表
     */
    public function addFile($fileFullPath, $fileName) {
        $opsFile = new Ancun\AncunOpsFile($fileFullPath, $fileName);
        array_push($this->list, $opsFile);
        return $this->list;
    }

    /**
     * 生成保全PDF文件
     *
     * @param $fileFullPath  要保存文件位置的完整路径名称
     * @param $username      用户名称
     *
     * @return mixed   包含完整路径的pdf文件
     */
    public function createPdfFile($fileFullPath, $username) {
        if(!$this->checkSavePath($fileFullPath)){
            return false;
        }
        $content = "<style>body{font-family:'宋体', 'Helvetica' ,'Arial'}</style>";
        $content .= '<h1 align="center">电子交易保全文件</h1><h2 align="right">' . $username . '保全文件</h2><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>';
        $content .= '<table width="100%" border="0"><tbody><tr>';
        $content .= '<td><b>投资人章</b>: 电子签章投资章专用</td>';
        $content .= '<td><b>借款人章</b>: 电子签章借款章专用</td>';
        $content .= '</tr></tbody></table>';
        if(substr($fileFullPath, -1) != DIRECTORY_SEPARATOR) {
            $fileFullPath .= DIRECTORY_SEPARATOR;
        }
        $filename = $fileFullPath . $username;
        return $this->SavePdfFile($filename, $content);
    }


    /**
     * 生成pdf文件
     *
     * @param $filename  保存的文件名称
     * @param $content   内容
     *
     * @return mixed     文件
     */
    public function savePdfFile($filename, $content) {
        vendor("mPDF.mpdf");
        $mpdf = new \mPDF('utf-8', 'A4', '', '黑体', 25, 25, 25, 25); //'utf-8' 或者 '+aCJK' 或者 'zh-CN'都可以显示中文
        //设置字体，解决中文乱码
        $mpdf->useAdobeCJK      = TRUE;
        $mpdf->autoScriptToLang = TRUE;
        $mpdf->autoLangToFont   = TRUE;
        $mpdf->SetDisplayMode('fullpage');
        $mpdf->h2bookmarks   = ['H3' => 0, 'H4' => 1, 'H5' => 2];
        $mpdf->mirrorMargins = 1;
        //是否缩进列表的第一级
        $mpdf->list_indent_first_level = 0;
        //导入外部css文件：
        //$stylesheet1 = file_get_contents(CSS_PATH . 'target.css');
        //$mpdf->WriteHTML($stylesheet1, 1);
        $mpdf->WriteHTML($content);  //$html中的内容即为变成pdf格式的html内容。
        $mpdf->Output($filename, "F");
        return $filename;
    }

    /**
     * 返回错误信息
     * @return mixed
     */
    public function getErrorMsg(){
        if($this->errorMsg){
            return $this->errorMsg;
        }
        if($this->opsResponse){
            return $this->opsResponse->Msg;
        }
    }

    /**
     * @param $savepath
     *
     * @return bool
     */
    private function checkSavePath($savepath) {
        if(!$this->mkdir($savepath)) {
            return FALSE;
        } else {
            /* 检测目录是否可写 */
            if(!is_writable($savepath)) {
                $this->errorMsg = '目录 ' . $savepath . ' 不可写！';
                return FALSE;
            } else {
                return TRUE;
            }
        }
    }

    /**
     * 创建目录
     *
     * @param  string $savepath 要创建的目录
     *
     * @return boolean          创建状态，true-成功，false-失败
     */
    private function mkdir($savepath) {
        $dir = $savepath;
        if(is_dir($dir)) {
            return TRUE;
        }

        if(mkdir($dir, 0777, TRUE)) {
            return TRUE;
        } else {
            $this->errorMsg = "目录 {$savepath} 创建失败！";
            return FALSE;
        }
    }
}